package kr.hkit.android_bookmgr.parser;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.R.integer;
import android.util.Log;
import kr.hkit.android_bookmgr.DTO.BookData;

public class SearchParser { //네이버 api - 사용

	private String key;
	ArrayList<BookData> data;
	
	public SearchParser(String key){
		this.key=key;
	}
	
	public ArrayList<BookData> getBookData(final String qry,final int count,final int start){
		data=new ArrayList<BookData>();
		
		BookData item=null;
		
		String m_searchinfo="";
		
		try{
			m_searchinfo=URLEncoder.encode(qry, "UTF8"); // 검색정보 인코딩
		} catch(UnsupportedEncodingException e1){
			e1.printStackTrace();
		}
		
		try{
			URL text= new URL(
					"http://openapi.naver.com/search?key=" + key + "&query="
					+ m_searchinfo + "&display=" + count 
					+ "&start=" + start + "&target=book"); //네이버 api URL 사용
			                                               //개발자 센터 참조
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser=parserCreator.newPullParser();
			
			parser.setInput(text.openStream(),null);
			
			// 읽어온 정보를 파싱하여 데이터를 만든다.
			int parseEvent = parser.getEventType();
			
			while(parseEvent != XmlPullParser.END_DOCUMENT){
				
				switch(parseEvent){
				
				case XmlPullParser.START_TAG:
					String tag=parser.getName();
					
					if(tag.compareTo("title")==0){
						item=new BookData();
						String titlesrc = parser.nextText();
						item.name = titlesrc;
					}
					
					if(tag.compareTo("description")==0){
						String descriptionsrc = parser.nextText();
						item.description = descriptionsrc;
					} 
					
					if(tag.compareTo("image")==0){
						String imagesrc = parser.nextText();
						item.bookimg=imagesrc;
					}
					if(tag.compareTo("price")==0){
						String pricesrc = parser.nextText();
						item.price=pricesrc;
					}
					if(tag.compareTo("author")==0){
						String authorsrc = parser.nextText();
						item.author = authorsrc;
					}
					if(tag.compareTo("publisher")==0){
						String publishersrc = parser.nextText();
						item.publisher = publishersrc;
						
						data.add(item);
					}
					break;
				}
				parseEvent = parser.next();
				// 다음 데이터로 넘어간다.. END_DOCUMENT일때까지..
			}
		} catch(Exception e){;}
		return data;
	}

}
